
<!DOCTYPE html>
<html lang="">


<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020"/>
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="/js/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content="Emberjs,Ember-Teach,Ember-Object," />
  

  
    <meta name="description" content="一个专注一coding的网站。提供丰富编程知识，包括Spring、Java、EmberJS、SpringBoot等等技术。" />
  
  
  <link rel="icon" type="image/x-icon" href="/image/favicon.ico">
  <title>观察者（observer） [ Keep Coding ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="/css/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
<meta name="generator" content="Hexo 5.0.2"><link rel="alternate" href="/atom.xml" title="Keep Coding" type="application/atom+xml">
</head>

<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    <img class="avatar" src="/image/favicon.ico">
    <span class="title">Keep Coding</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/archives" class="pure-menu-link">归档</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/tags" class="pure-menu-link">标签</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/search" class="pure-menu-link">搜索</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/about" class="pure-menu-link">关于</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/atom.xml" class="pure-menu-link">订阅</a></li>
          
      
  </ul>
   
</nav>
  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner">
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        观察者（observer）
      </h1>
      <span>
        
        <time class="time" datetime="2020-01-18T14:50:37.000Z">
        2020-01-18
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Object/" rel="tag">Ember-Object</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Teach/" rel="tag">Ember-Teach</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Emberjs/" rel="tag">Emberjs</a></li></ul>
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
      <span class="read">阅读耗时 4 分钟</span>
    </header>

    <div class="post-content">
      <blockquote>
<p><code>Ember</code>可以检测任何属性的变化，包括计算属性。</p>
</blockquote>
<h3 id="观察者使用"><a href="#观察者使用" class="headerlink" title="观察者使用"></a>观察者使用</h3><p><code>Ember</code>可以察觉所有属性的变化，包括计算属性。观察者是非常有用的，特别是计算属性绑定之后需要同步的时候。<br>观察者经常被Ember开发过度使用。<code>Ember</code>框架本身已经大量使用观察者，但是对于大多数的开发者面对开发问题时使用计算属性是更适合的解决方案。<br>使用方式：可以用<code>Ember.observer</code>创建一个对象为观察者。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Observer对于Emberjs来说非常重要，前面你看到的很多代码都是与它有关系，计算属性之所以能更新也是因为它</span></span><br><span class="line">Person = Ember.Object.extend(&#123;</span><br><span class="line">  firstName: <span class="literal">null</span>,</span><br><span class="line">  lastName: <span class="literal">null</span>,</span><br><span class="line"></span><br><span class="line">  fullName: Ember.computed(<span class="string">&#x27;firstName&#x27;</span>, <span class="string">&#x27;lastName&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.get(<span class="string">&#x27;firstName&#x27;</span>) + <span class="string">&quot; &quot;</span> + <span class="built_in">this</span>.get(<span class="string">&#x27;lastName&#x27;</span>);</span><br><span class="line">  &#125;),</span><br><span class="line"></span><br><span class="line">  <span class="comment">//  当fullName被改变的时候触发观察者</span></span><br><span class="line">  fullNameChange: Ember.observer(<span class="string">&#x27;fullName&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;The fullName is changed by caller&quot;</span>);</span><br><span class="line">    <span class="comment">//return this.get(&#x27;fullName&#x27;);</span></span><br><span class="line">  &#125;)</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> person = Person.create(&#123;</span><br><span class="line">  firstName: <span class="string">&#x27;chen&#x27;</span>,</span><br><span class="line">  lastName: <span class="string">&#x27;ubuntuvim&#x27;</span></span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// 如果被观察的计算属性还没执行过get()方法不会触发观察者</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;fullName = &#x27;</span> + person.get(<span class="string">&#x27;fullName&#x27;</span>));  </span><br><span class="line"><span class="comment">//  fullName是依赖firstName和lastName的，这里改变了firstName的值，计算属性会自动更新，</span></span><br><span class="line"><span class="comment">//  fullName被改变了所以会触发观察者</span></span><br><span class="line">person.set(<span class="string">&#x27;firstName&#x27;</span>, <span class="string">&#x27;change firstName value&#x27;</span>);  <span class="comment">// 观察者会被触发</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;fullName = &#x27;</span> + person.get(<span class="string">&#x27;fullName&#x27;</span>));</span><br></pre></td></tr></table></figure>

<p><code>fullName</code>是依赖<code>firstName</code>和<code>lastName</code>的，调用<code>set()</code>方法改变了<code>firstName</code>的值，自然的导致<code>fullName</code>的值也被改变了，<code>fullName</code>变化了就触发观察者。从执行的结果就可以看出来；</p>
<p><img src="http://static.oschina.net/uploads/img/201509/08215431_TNgu.png" alt="运行结果图"></p>
<p><code>Ember</code>还为开发者提供了另一种使用观察者的方式。这种方式使你可以在类定义之外为某个计算属性增加一个观察者。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">person.addObserver(<span class="string">&#x27;fullName&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// deal with the change…</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h3 id="观察者与异步"><a href="#观察者与异步" class="headerlink" title="观察者与异步"></a>观察者与异步</h3><p>目前，观察者在<code>Ember</code>中是同步的（不是笔误，官网就是这么说的<code>Observers in Ember are currently synchronous.</code>）。这就意味着只要计算属性一发生变化就会触发观察者。也因为这个原因很容易就会引入这样的<code>bug</code>在计算属性没有同步的时候。比如下面的代码；</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Person.reopen(&#123;</span><br><span class="line">  lastNameChanged: Ember.observer(<span class="string">&#x27;lastName&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// The observer depends on lastName and so does fullName. Because observers</span></span><br><span class="line">    <span class="comment">// are synchronous, when this function is called the value of fullName is</span></span><br><span class="line">    <span class="comment">// not updated yet so this will log the old value of fullName</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">this</span>.get(<span class="string">&#x27;fullName&#x27;</span>));</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>然而由于同步的原因如果你的的观察者同时观察多个属性，就会导致观察者执行多次。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">person = Ember.Object.extend(&#123;</span><br><span class="line">  firstName: <span class="literal">null</span>,</span><br><span class="line">  lastName: <span class="literal">null</span>,</span><br><span class="line"></span><br><span class="line">  fullName: Ember.computed(<span class="string">&#x27;firstName&#x27;</span>, <span class="string">&#x27;lastName&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.get(<span class="string">&#x27;firstName&#x27;</span>) + <span class="string">&quot; &quot;</span> + <span class="built_in">this</span>.get(<span class="string">&#x27;lastName&#x27;</span>);</span><br><span class="line">  &#125;),</span><br><span class="line"></span><br><span class="line">  <span class="comment">//  当fullName被改变的时候触发观察者</span></span><br><span class="line">  fullNameChange: Ember.observer(<span class="string">&#x27;fullName&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;The fullName is changed by caller&quot;</span>);</span><br><span class="line">    <span class="comment">//return this.get(&#x27;fullName&#x27;);</span></span><br><span class="line">  &#125;)</span><br><span class="line">&#125;);</span><br><span class="line">Person.reopen(&#123;</span><br><span class="line">  partOfNameChanged: Ember.observer(<span class="string">&#x27;firstName&#x27;</span>, <span class="string">&#x27;lastName&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">//  同时观察了firstName和lastName两个属性</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;========partOfNameChanged======&#x27;</span>);</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;);</span><br><span class="line"><span class="keyword">var</span> person = Person.create(&#123;</span><br><span class="line">  firstName: <span class="string">&#x27;chen&#x27;</span>,</span><br><span class="line">  lastName: <span class="string">&#x27;ubuntuvim&#x27;</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">person.set(<span class="string">&#x27;firstName&#x27;</span>, <span class="string">&#x27;[firstName]&#x27;</span>);</span><br><span class="line">person.set(<span class="string">&#x27;lastName&#x27;</span>, <span class="string">&#x27;[lastName]&#x27;</span>);</span><br></pre></td></tr></table></figure>

<p><img src="http://static.oschina.net/uploads/img/201509/08215431_5Zli.png" alt="run result"></p>
<p>显然上述代码执行了两次<code>set()</code>所以观察者也会执行2次，但是如果开发中需要设置只能执行一次观察出呢？Ember提供了一个<code>once()</code>方法，这个方法会在下一次循环所有绑定属性都同步的时候执行。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">Person = Ember.Object.extend(&#123;</span><br><span class="line">  firstName: <span class="literal">null</span>,</span><br><span class="line">  lastName: <span class="literal">null</span>,</span><br><span class="line"></span><br><span class="line">  fullName: Ember.computed(<span class="string">&#x27;firstName&#x27;</span>, <span class="string">&#x27;lastName&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.get(<span class="string">&#x27;firstName&#x27;</span>) + <span class="string">&quot; &quot;</span> + <span class="built_in">this</span>.get(<span class="string">&#x27;lastName&#x27;</span>);</span><br><span class="line">  &#125;),</span><br><span class="line"></span><br><span class="line">  <span class="comment">//  当fullName被改变的时候触发观察者</span></span><br><span class="line">  fullNameChange: Ember.observer(<span class="string">&#x27;fullName&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;The fullName is changed by caller&quot;</span>);</span><br><span class="line">    <span class="comment">//return this.get(&#x27;fullName&#x27;);</span></span><br><span class="line">  &#125;)</span><br><span class="line">&#125;);</span><br><span class="line">Person.reopen(&#123;</span><br><span class="line">  partOfNameChanged: Ember.observer(<span class="string">&#x27;firstName&#x27;</span>, <span class="string">&#x27;lastName&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">//  同时观察了firstName和lastName两个属性</span></span><br><span class="line">    <span class="comment">//  方法partOfNameChanged本身还是会执行多次，但是方法processFullName只会执行一次</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;========partOfNameChanged======&#x27;</span>);  <span class="comment">//  </span></span><br><span class="line">    Ember.run.once(<span class="built_in">this</span>, <span class="string">&#x27;processFullName&#x27;</span>);</span><br><span class="line">  &#125;),</span><br><span class="line">  processFullName: Ember.observer(<span class="string">&#x27;fullName&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 当你同时设置多个属性的时候，此观察者只会执行一次，并且是发生在下一次所有属性都被同步的时候</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;fullName = &#x27;</span> + <span class="built_in">this</span>.get(<span class="string">&#x27;fullName&#x27;</span>));</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> person = Person.create(&#123;</span><br><span class="line">  firstName: <span class="string">&#x27;chen&#x27;</span>,</span><br><span class="line">  lastName: <span class="string">&#x27;ubuntuvim&#x27;</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">person.set(<span class="string">&#x27;firstName&#x27;</span>, <span class="string">&#x27;[firstName]&#x27;</span>);</span><br><span class="line">person.set(<span class="string">&#x27;lastName&#x27;</span>, <span class="string">&#x27;[lastName]&#x27;</span>);</span><br></pre></td></tr></table></figure>

<p><img src="http://static.oschina.net/uploads/img/201509/08215431_xi6t.png" alt="run result"></p>
<h3 id="观察者与对象初始化"><a href="#观察者与对象初始化" class="headerlink" title="观察者与对象初始化"></a>观察者与对象初始化</h3><p>观察者一直到对象初始化完成之后才会执行。<br>如果你想观察者在对象初始化的时候就执行你必须要手动调用<code>Ember.on()</code>方法。这个方法会在对象初始化之后就执行。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">Person = Ember.Object.extend(&#123;</span><br><span class="line">  salutation:<span class="literal">null</span>,</span><br><span class="line">  init() &#123;</span><br><span class="line">    <span class="built_in">this</span>.set(<span class="string">&#x27;salutation&#x27;</span>, <span class="string">&#x27;hello&#x27;</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;init....&#x27;</span>);</span><br><span class="line">  &#125;,</span><br><span class="line">  salutationDidChange: Ember.on(<span class="string">&#x27;init&#x27;</span>, Ember.observer(<span class="string">&#x27;salutation&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;salutationDidChange......&#x27;</span>);</span><br><span class="line">  &#125;))</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> p = Person.create();</span><br><span class="line">p.get(<span class="string">&#x27;salutationDidChange&#x27;</span>);  <span class="comment">//  output &gt; init....  salutationDidChange......</span></span><br><span class="line"><span class="built_in">console</span>.log(p.get(<span class="string">&#x27;salutation&#x27;</span>));  <span class="comment">// output &gt; hello</span></span><br><span class="line">p.set(<span class="string">&#x27;salutation&#x27;</span>);  <span class="comment">//  output &gt; salutationDidChange......</span></span><br></pre></td></tr></table></figure>

<h3 id="未获取过值的计算属性不会触发观察者"><a href="#未获取过值的计算属性不会触发观察者" class="headerlink" title="未获取过值的计算属性不会触发观察者"></a>未获取过值的计算属性不会触发观察者</h3><p>如果一个计算属性从来没有调用过<code>get()</code>方法获取的其值，观察者就不会被触发，即使是计算属性的值发生变化了。你可以这么认为，观察者是根据调用<code>get()</code>方法前后的值比较判断出计算属性值是否发生改变了。如果没调用过<code>get()</code>之前的改变观察者认为是没有变化。<br>  通常我们不需要担心这个问题会影响到程序代码，因为几乎所有被观察的计算属性在触发前都会执行取值操作。如果你仍然担心观察者不会被触发，你可以在<code>init()</code>方法了执行一次<code>get</code>操作。这样足以保证你的观察在触发之前是执行过get操作的。<br><br><br>对于初学者来说，属性值的自动更新还是有点难以理解，到底它是怎么个更新法！！！先别急，先放一放，随着不断深入学习你就会了解到这个是多么强大的特性。<br><br><br>博文完整代码放在<a target="_blank" rel="noopener" href="https://github.com/ubuntuvim/my_emberjs_code">Github</a>（博文经过多次修改，博文上的代码与github代码可能又出入，不过影响不大！），如果你觉得博文对你有点用在github项目上给我个<code>star</code>吧。您的肯定对我来说是最大的动力！！</p>

    </div>

      
    <div class="post-nav">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/01/18/ember-teach/components/%E5%8C%85%E8%A3%B9%E5%86%85%E5%AE%B9/" rel="next" title="包裹内容">
          包裹内容
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/01/18/ember-teach/The%20Object%20Model/%E7%BB%91%E5%AE%9A%EF%BC%88bingding%EF%BC%89/" rel="prev" title="绑定（bingding）">
            绑定（bingding）
          </a>
          <span>〉</span>
        
      </div>
    </div>
  
  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A7%82%E5%AF%9F%E8%80%85%E4%BD%BF%E7%94%A8"><span class="toc-text">观察者使用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A7%82%E5%AF%9F%E8%80%85%E4%B8%8E%E5%BC%82%E6%AD%A5"><span class="toc-text">观察者与异步</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A7%82%E5%AF%9F%E8%80%85%E4%B8%8E%E5%AF%B9%E8%B1%A1%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-text">观察者与对象初始化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9C%AA%E8%8E%B7%E5%8F%96%E8%BF%87%E5%80%BC%E7%9A%84%E8%AE%A1%E7%AE%97%E5%B1%9E%E6%80%A7%E4%B8%8D%E4%BC%9A%E8%A7%A6%E5%8F%91%E8%A7%82%E5%AF%9F%E8%80%85"><span class="toc-text">未获取过值的计算属性不会触发观察者</span></a></li></ol>
  </div>


  </div>
</div>


<div class="copyright">
    <span>本作品采用</span>
    <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>
<div class="share">

</div>
<div class="post-container">
    <article class="post">
      <div id="container"></div>
    </article>
</div>

<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
<script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
<script>
var gitment = new Gitment({
  id: '观察者（observer）', // 可选。默认为 location.href
  owner: 'ubuntuvim',
  repo: 'ubuntuvim.github.io',
  oauth: {
    client_id: '48b3df0bf4ba1743e0a3',
    client_secret: 'c6c2cec09acb5eecc9d325d56cef187264aa1e16',
  },
})
gitment.render('container')
</script>



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href="http://xcoding.tech/">首页</a> |
        <a class="bottom-item" href="http://xcoding.tech/" target="_blank">主站</a> |
        <a class="bottom-item" href="https://github.com/ubuntuvim" target="_blank">GitHub</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/KevinOfNeu/hexo-theme-xoxo" target="_blank">Theme xoxo</a>
    </div>
</footer>


  <script src='https://unpkg.com/mermaid@7.1.2/dist/mermaid.min.js'></script>
  <script>
    if (window.mermaid) {
      mermaid.initialize({theme: 'forest'});
    }
  </script>


  
  <!-- scripts list from theme config.yml -->
  
    <script src="/js/zepto.min.js"></script>
  


<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



</body>
</html>
